package com.mornd.gulimall.product.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mornd.gulimall.common.core.result.AjaxResult;
import com.mornd.gulimall.common.core.validation.UpdateGroup;
import com.mornd.gulimall.product.entity.Brand;
import com.mornd.gulimall.product.service.IBrandService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * <p>
 * 品牌 前端控制器
 * </p>
 *
 * @author mornd
 * @since 2023-07-23
 */

//@Validated
@RestController
@RequestMapping("/product/brand")
public class BrandController {
    @Resource
    private IBrandService brandService;

    @GetMapping
    public AjaxResult list(Brand brand) {
        IPage<Brand> page = brandService.pageList(brand);
        return AjaxResult.success(page);
    }

    @GetMapping("/{id}")
    public AjaxResult getById(@PathVariable Long id) {
        Brand brand = brandService.getById(id);
        return AjaxResult.success(brand);
    }

    @PutMapping
    public AjaxResult save(@Validated @RequestBody Brand brand) {
        if (brandService.existsName(null, brand.getName())) {
            return AjaxResult.error("添加失败，名称已重复");
        }
        if (brand.getSort() == null) {
            brand.setSort(0);
        }
        brand.setBrandId(null);
        brandService.save(brand);
        return AjaxResult.success();
    }

    @PostMapping
    public AjaxResult update(@RequestBody @Validated(UpdateGroup.class) Brand brand) {
        if (brandService.existsName(brand.getBrandId(), brand.getName())) {
            return AjaxResult.error("修改失败，名称已重复");
        }
        brandService.updateCascade(brand);
        return AjaxResult.success();
    }

    @DeleteMapping("/{ids}")
    public AjaxResult delete(@PathVariable Long[] ids) {
        brandService.removeByIds(Arrays.asList(ids));
        return AjaxResult.success();
    }

    /**
     * 根据分类id查询品牌
     *
     * @param catId
     * @return
     */
    @GetMapping("/listByCatId/{catId}")
    public AjaxResult listByCatId(@PathVariable Long catId) {
        return AjaxResult.success(brandService.listByCatId(catId));
    }
}
